//
//  YKHTTPService.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/6/23.
//

#import "YKHTTPService.h"
#import "YKHTTPSignatureManager.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import "../../Utils/Network/IMNetworkUtils.h"

@interface YKHTTPService ()
@property (nonatomic, strong) YKHTTPServiceConfig *config;
@property (nonatomic, assign) BOOL isInitialized;
@end

@implementation YKHTTPService

static YKHTTPService *_sharedService = nil;
static dispatch_once_t _onceToken;

+ (instancetype)sharedService {
    dispatch_once(&_onceToken, ^{
        _sharedService = [[YKHTTPService alloc] init];
    });
    return _sharedService;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _config = [YKHTTPServiceConfig sharedConfig];
        _isInitialized = NO;
    }
    return self;
}

#pragma mark - 配置方法

+ (void)configureWithProductionURL:(NSString *)productionURL
                           testURL:(NSString *)testURL
                           signKey:(NSString *)signKey
                       gameVersion:(NSString *)gameVersion
                        sdkVersion:(NSString *)sdkVersion {
    
    YKHTTPService *service = [self sharedService];
    
    // 配置HTTP服务
    [service.config configureWithProductionURL:productionURL
                                        testURL:testURL
                                        signKey:signKey
                                    gameVersion:gameVersion
                                     sdkVersion:sdkVersion];
    
    // 初始化网络工具
    [self setupNetworkUtils];
    
    service.isInitialized = YES;
    
    [IMLogUtils info:IMLogTagNetwork format:@"[YKHTTPService] HTTP服务配置完成"];
}

+ (void)switchToProduction {
    [[self sharedService].config switchToProduction];
    [self setupNetworkUtils];
}

+ (void)switchToTest {
    [[self sharedService].config switchToTest];
    [self setupNetworkUtils];
}

+ (YKHTTPServiceConfig *)currentConfig {
    return [self sharedService].config;
}

#pragma mark - HTTP请求方法

+ (IMNetworkTask *)GET:(NSString *)path
            parameters:(NSDictionary *)parameters
               success:(IMNetworkSuccessBlock)success
               failure:(IMNetworkFailureBlock)failure {
    
    return [self requestWithMethod:IMNetworkMethodGET
                              path:path
                        parameters:parameters
                           success:success
                           failure:failure];
}

+ (IMNetworkTask *)POST:(NSString *)path
             parameters:(NSDictionary *)parameters
                success:(IMNetworkSuccessBlock)success
                failure:(IMNetworkFailureBlock)failure {
    
    return [self requestWithMethod:IMNetworkMethodPOST
                              path:path
                        parameters:parameters
                           success:success
                           failure:failure];
}

+ (IMNetworkTask *)PUT:(NSString *)path
            parameters:(NSDictionary *)parameters
               success:(IMNetworkSuccessBlock)success
               failure:(IMNetworkFailureBlock)failure {
    
    return [self requestWithMethod:IMNetworkMethodPUT
                              path:path
                        parameters:parameters
                           success:success
                           failure:failure];
}

+ (IMNetworkTask *)DELETE:(NSString *)path
               parameters:(NSDictionary *)parameters
                  success:(IMNetworkSuccessBlock)success
                  failure:(IMNetworkFailureBlock)failure {
    
    return [self requestWithMethod:IMNetworkMethodDELETE
                              path:path
                        parameters:parameters
                           success:success
                           failure:failure];
}

#pragma mark - 工具方法

+ (NSString *)currentEnvironmentDescription {
    return [[self sharedService].config currentEnvironmentDescription];
}

+ (BOOL)isConfigured {
    return [self sharedService].isInitialized;
}

#pragma mark - Private Methods

+ (void)setupNetworkUtils {
    YKHTTPServiceConfig *config = [self sharedService].config;
    
    // 创建网络配置
    IMNetworkConfig *networkConfig = [IMNetworkConfig defaultConfig];
    networkConfig.baseURL = config.currentBaseURL;
    networkConfig.timeoutInterval = config.timeoutInterval;
    networkConfig.enableLogging = config.enableLogging;
    networkConfig.maxRetryCount = config.maxRetryCount;
    
    // 初始化网络工具
    [IMNetworkUtils initWithConfig:networkConfig];
    
    [IMLogUtils debug:IMLogTagNetwork format:@"[YKHTTPService] 网络工具配置完成，baseURL: %@", config.currentBaseURL];
}

+ (IMNetworkTask *)requestWithMethod:(IMNetworkMethod)method
                                path:(NSString *)path
                          parameters:(NSDictionary *)parameters
                             success:(IMNetworkSuccessBlock)success
                             failure:(IMNetworkFailureBlock)failure {
    
    if (![self isConfigured]) {
        [IMLogUtils error:IMLogTagError format:@"[YKHTTPService] HTTP服务未配置，请先调用配置方法"];
        
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"YKHTTPServiceError"
                                                 code:-1001
                                             userInfo:@{NSLocalizedDescriptionKey: @"HTTP服务未配置"}];
            
            IMNetworkResponse *response = [[IMNetworkResponse alloc] initWithData:nil
                                                                        statusCode:0
                                                                           headers:nil
                                                                             error:error
                                                                          duration:0
                                                                         requestID:@""];
            failure(response);
        }
        return nil;
    }
    
    YKHTTPServiceConfig *config = [self sharedService].config;
    
    // 构建完整的请求参数（包含公共参数和签名）
    NSDictionary *finalParameters = nil;
    if (config.enableSignature) {
        finalParameters = [YKHTTPSignatureManager buildRequestParameters:parameters
                                                                  signKey:config.signKey
                                                              gameVersion:config.gameVersion
                                                               sdkVersion:config.sdkVersion
                                                                 timezone:config.timezone];
        
        // 生成并打印Postman参数
        NSString *postmanParams = [YKHTTPSignatureManager generatePostmanParametersWithOriginalParams:parameters
                                                                                              signKey:config.signKey
                                                                                          gameVersion:config.gameVersion
                                                                                           sdkVersion:config.sdkVersion
                                                                                             timezone:config.timezone];
        [IMLogUtils debug:IMLogTagNetwork format:@"\n\n===== Postman 参数 =====\n%@\n=======================\n\n", postmanParams];
        
    } else {
        finalParameters = [YKHTTPSignatureManager addCommonParameters:parameters
                                                           gameVersion:config.gameVersion
                                                            sdkVersion:config.sdkVersion
                                                              timezone:config.timezone];
    }
    
    // 发起网络请求
    return [IMNetworkUtils request:method
                         URLString:path
                        parameters:finalParameters
                           headers:nil
                           success:success
                           failure:failure];
}

@end